package com.raos.validation.util;

import com.raos.validation.response.RRException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * <p>
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/5/16 20:48
 */
public class ValidatorUtils {

    private ValidatorUtils() { }

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws RRException 校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws RRException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);

        if (!constraintViolations.isEmpty()) {
            Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();
            StringBuilder msg = new StringBuilder();
            while (iterator.hasNext()) {
                ConstraintViolation<Object> constraint = iterator.next();
                msg.append(constraint.getMessage()).append(',');
            }
//            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new RRException(msg.toString().substring(0,msg.toString().lastIndexOf(',')));
        }

    }

}
